package com.learn.springboot.controller;

import static com.learn.springboot.service.utils.TokenUtil.ADMIN_TOKEN;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.learn.springboot.dao.request.LoginRequest;
import com.learn.springboot.dao.request.ResponseManage;
import com.learn.springboot.dao.response.CommonResponse;
import com.learn.springboot.service.utils.TokenUtil;

import cn.hutool.crypto.digest.MD5;

/**
 * @author suzheng
 * @date 2024-05-13
 **/
@Controller
@RequestMapping("/api")
public class LoginController {

    @ResponseBody
    @PostMapping("/login")
    CommonResponse login(LoginRequest request, HttpServletResponse response) {
        if (!"admin".equalsIgnoreCase(request.getUserName())) {
            return ResponseManage.fail("用户名错误");
        }
        String md5Str = MD5.create().digestHex("sucai@admin");
        if (!md5Str.equalsIgnoreCase(request.getPassword())) {
            return ResponseManage.fail("密码错误");
        }
        String token = TokenUtil.generateToken(request.getUserName());
        response.addHeader(ADMIN_TOKEN,token);
        return ResponseManage.success();
    }

    @ResponseBody
    @PostMapping("/logout")
    CommonResponse logout(HttpServletRequest request) {
       String token= request.getHeader(ADMIN_TOKEN);
       TokenUtil.delToken(token);
        return ResponseManage.success();
    }
}
